// mypage/myOrder/myOrder.js
var app=getApp();
var util = require("../../utils/util");
var my=require("../../api/my");
var home=require("../../api/home");
const group = require("../../api/group");


Page({
  /*页面的初始数据*/
  data: {
    num1: 0,
    num2: 0,
    num3: 0,
    width: wx.getSystemInfoSync().windowWidth,
    nav_index: 5,
    order_index: '',
    order_id: '',
    refund_show: true,
    del_show: true,
    call_show: true,
    pop_show: true,
    ver_show: true,
    ver_number: '',
    show_com: 0,
    apply_list: ['不想买了','课程买错了','课程质量问题'],
    apply_index: 1000,
    com_data: [],
    order_list:[],
    currentPage: 1,
    pageSize: 10,
    hasMoreData: true,
    timer: '',
    timeGroup: '',
    token: '',
    pay_act: true,
    show_nav: false,
    activity_id: '1344172560662351873',
    join_index: ''
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that = this;
    that.setData({city:wx.getStorageSync('city'),userinfo:wx.getStorageSync('userinfo')});
    wx.getStorage({
      key: 'token',
      success:function(res){
        that.setData({token:res.data})
        //
        that.get_order_count()
        if(options.type){
          if(options.type==2){
            that.setData({nav_index:2})
            that.get_order_list(2)
          }else{
            that.get_group_order()
          }
        }else{
          that.get_group_order()
        }
      }
    })
  },
  // 切换
  check_nav:function(e){
    var that = this,nav_index=that.data.nav_index;
    var index = e.currentTarget.dataset.index;
    if(nav_index != index){
      that.setData({nav_index:index,order_list:[],currentPage:1,show_nav:false})
      if(index==5){
        that.get_group_order()
      }else{
        //
        that.get_order_list(index)
      }
    }
    var cur = e.currentTarget.dataset.num;
    var curWidth = (that.data.width - 30) / 3;
    var moveWidth = (cur - 1) * curWidth
    if (moveWidth > 0) {
      that.setData({ scrollLeft: moveWidth })
    } else {
      that.setData({ scrollLeft: 0 })
    }
  },
  // 查询订单课程套餐详情
  open_more:function(e){
    var that=this,order_list=that.data.order_list;
    var index=e.currentTarget.dataset.index,id=e.currentTarget.dataset.id;
    if(!order_list[index].show_more){
      that.get_meal_detail(id,index)
    }
    for(var i=0;i<order_list.length;i++){
      order_list[i].show_more=false
    }
    that.setData({order_list:order_list})
  },
  // 跳转
  nav_mech:function(e){
    var id=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../pages/mechDetail/mechDetail?id='+id+'&status=7',
    })
  },
  // 跳转课程详情
  nav_courDetail:function(e){
    var that=this;
    var id=e.currentTarget.dataset.id,aid=e.currentTarget.dataset.aid,type=e.currentTarget.dataset.type?e.currentTarget.dataset.type:2;
    if(type==1){
      that.get_course_type(id)
    }else if(type==2){
      util.page_show_toast("此商品已下架",2000)
    }else if(type==4){
      that.get_group_type(aid)
    }
  },
  // 跳转拼团详情
  nav_groupDetail:function(e){
    var that=this;
    var id=e.currentTarget.dataset.id;
    //
    that.get_group_type(id)
  },
  // 去支付(待支付订单)
  user_pay_order:function(e){
    var that=this,token=that.data.token,order_list=that.data.order_list,pay_act=that.data.pay_act,cour_details=wx.getStorageSync('cour_details');
    var orderNo=e.currentTarget.dataset.num,index=e.currentTarget.dataset.index;
    var orderId=order_list[index].id,order_price=order_list[index].paidInAmount,pref_money=order_list[index].businessDiscountAmount+order_list[index].platformDiscountAmount,targetType=order_list[index].targetType,group_aid=order_list[index].activityId;
    cour_details.id=order_list[index].targetId;
    cour_details.img=order_list[index].commodityImg[0];
    cour_details.name=order_list[index].commodityName;
    // targetType 1-课程  4-拼团
    if(order_list[index].targetType==4){
      // 活动详情(修改课程缓存)
      that.get_cour_and_group(order_list[index].activityId,cour_details)
    }
    if(pay_act){
      //
      that.pay_order(orderId,orderNo,token,order_price,pref_money,targetType,1,group_aid)
    }
    that.setData({pay_act:false})
  },
  // 拼团单-继续支付
  pay_on_order:function(e){
    var that=this,pay_act=that.data.pay_act;
    var index=e.currentTarget.dataset.index;
    if(pay_act){
      that.create_goup_order(index)
    }
  },
  // 退款弹窗
  open_refundMask:function(e){
    var that = this,order_list=that.data.order_list;
    var index=e.currentTarget.dataset.index;
    if(order_list[index].reverseStatus == 1){
      this.setData({refund_show: !this.data.refund_show,order_index: index})
    }else{
      util.page_show_toast('该订单已核销',2000)
    }
  },
  close_refundMask:function(){
    this.setData({refund_show: !this.data.refund_show})
  },
  // 确认退款
  check_apply:function(e){
    var that=this;
    that.setData({apply_index:e.detail})
  },
  confirm_apply:function(e){
    var that=this,apply_list=that.data.apply_list,order_index=that.data.order_index,order_list=that.data.order_list,token=that.data.token,apply_index=that.data.apply_index;
    //
    var params={
      "orderNo": order_list[order_index].orderNo,
      "desc": apply_list[apply_index]
    }
    that.refund_order(params,token)
  },
  // 弹窗
  open_pop:function(e){
    var that=this,order_list=that.data.order_list;
    var num=e.currentTarget.dataset.num;
    that.setData({pop_show:!that.data.pop_show,show_com:num})
    if(num == 1){
      that.setData({refund_show:!this.data.refund_show,com_data:that.data.apply_list,apply_index:1000})
    }else if(num==2){
      var id=e.currentTarget.dataset.id,index = e.currentTarget.dataset.index;
      that.setData({order_index:index,order_id: id,phone:order_list[index].businessPhone,status:order_list[index].reverseStatus})
      that.get_less_list(id)
    }
  },
  colse_pop:function(e){
    var that = this;
    var obj = e.detail.pop_show;
    that.setData({pop_show: obj})
  },
  // 确认排课
  confirm_work:function(e){
    var that=this,id=that.data.order_id;
    //
    that.confirm_table(id);
  },
  // 取消排课
  cancel_work:function(e){
    var that=this,id=that.data.order_id;
    //
    that.cancel_table(id)
  },
  // 联系机构
  close_call:function(){
    this.setData({call_show:true})
  },
  call_mech:function(){
    var that=this,phone=that.data.phone;
    that.setData({call_show: true})
    wx.makePhoneCall({
      phoneNumber: phone,
      success:function(){},
      fail:function(){}
    })
  },
  // 核销码
  open_copy_pop:function(e){
    var that=this,order_list=that.data.order_list;
    var index=e.currentTarget.dataset.index;
    var ver_number=order_list[index].orderNo+order_list[index].verificationCode;
    that.setData({ver_number:ver_number,ver_show:false})
  },
  close_ver_pop:function(){
    this.setData({ver_show:!this.data.ver_show})
  },
  copy_ver_number:function(){
    var that=this,ver_number=that.data.ver_number;
    wx.setClipboardData({
      data: ver_number,
      success (res) {
        // 复制
        wx.getClipboardData({
          success (res) {
            that.close_ver_pop()
          }
        })
      }
    })
  },
  // 空数据
  swb_index:function(){
    wx.switchTab({
      url: '../../pages/home/home',
    })
  },
  return:function(){},
  // 用户取消订单
  user_cancel_order:function(e){
    var that=this,id=e.currentTarget.dataset.id,index=e.currentTarget.dataset.index;
    //
    that.cancel_order(id,index)
  },
  // 用户取消报名
  user_cancel_exp_order:function(e){
    var that=this,id=e.currentTarget.dataset.id,index=e.currentTarget.dataset.index;
    //
    that.cancel_exp_order(id,index)
  },
  // 用户删除订单
  open_delMask:function(e){
    var that=this;
    var id=e.currentTarget.dataset.id,index=e.currentTarget.index;
    that.setData({del_show:!that.data.del_show,order_id:id,order_index:index})
  },
  close_delMask:function(){
    this.setData({del_show:!this.data.del_show})
  },
  del_order:function(e){
    var that=this,id=that.data.order_id,index=that.data.order_index;
    //
    that.user_delt_order(id,index)
    that.close_delMask()
  },
  // 触底
  onReachBottom:function(){
    var that=this,hasMoreData=that.data.hasMoreData,nav_index=that.data.nav_index;
    if(hasMoreData){
      if(nav_index==5){
        that.get_group_order()
      }else{
        that.get_order_list(nav_index)
      }
    }else{
      util.page_show_toast('没有更多了',1500)
    }
  },
  // 分享
  onShareAppMessage:function(e){
    var that=this,order_list=that.data.order_list,name=that.data.userinfo.nickName,lessonTimes=that.data.lessonTimes;
    if(e.from=="button"){
      var index=e.target.dataset.index,id=order_list[index].order.setMealId,lessonTime=lessonTimes[index],group_id=order_list[index].order.groupFoundId,payStep=order_list[index].order.payStep,group_aid=order_list[index].order.activityId;
      return {
        title: order_list[index].order.commodityName,
        path: '/pages/payCourse/payCourse?id='+id+'&lessonTime='+lessonTime+'&type='+payStep+'&group_id='+group_id+'&group_aid='+group_aid,
        // path: '/pages/groupCourse/groupCourse?id='+order_list[index].order.activityId+'&type=2',
        imageUrl: order_list[index].order.commodityImg[0]
      }
    }else{
      return{
        title: name+'邀请您一起关注家巴啦',
        path: '/pages/home/home',
        imageUrl: 'https://ossdev0.jiabala.com/xaSpNcZEmBSRd'
      }
    }
  },
  // 监听页面初次渲染完成
  onReady: function () {
    this.dialog = this.selectComponent('#orderpop');
  },
  // 移除定时器
  onUnload: function () {
    clearInterval(this.data.timer);
    clearInterval(this.data.timeGroup);
  },
  // 待支付订单倒计时
  count_down:function(){
    var that=this,order_list=that.data.order_list;
    that.data.timer=setInterval(function(){
      for(var i=0;i<order_list.length;i++){
        var stepTime=(order_list[i].createTime/1000+30*60)-parseInt((new Date().getTime())/1000);
        var endTime=util.time2date(stepTime);
        if(stepTime>0){
          order_list[i].endTime=endTime
        }else{
          //删除订单
          that.cancel_order(order_list[i].id,i)
        }
      }
      that.setData({order_list: order_list})
    },1000)
  },
  // 拼团订单倒计时
  group_count_down:function(){
    var that=this,order_list=that.data.order_list;
    that.data.timeGroup=setInterval(function(){
      for(var i=0;i<order_list.length;i++){
        var stepTime= order_list[i].groupFound.endTime/1000-parseInt(new Date().getTime())/1000;
        var endTime=util.time3date(stepTime);
        if(stepTime>0){
          order_list[i].group_time=endTime
        }else{
          //删除订单
          // that.cancel_order(order_list[i].id,i)
        }
      }
      that.setData({order_list: order_list})
    },1000)
  },
  // 订单数量
  get_order_count:function(){
    var that=this,token=that.data.token;
    my.get_order_count(token).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        that.setData({num1:info.paidCount,num2:info.toBePaidCount,num3:info.refundedCount})
      }
    })
  },
  // 拼团中订单列表
  get_group_order:function(){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize,token=that.data.token,userinfo=that.data.userinfo,join_index='';
    var params={
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    group.get_group_order(params,token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records,lessonTimes=[];
        that.setData({num4:res.data.data.total})
        for(var i=0;i<list.length;i++){
          list[i].order.commodityImg=list[i].order.commodityImg?(list[i].order.commodityImg.indexOf("[")>-1?list[i].order.commodityImg.replace(/\[|]/g,'').split(","):list[i].order.commodityImg.split(",")):'';
          list[i].order.courseNatureName=list[i].order.courseNatureName?list[i].order.courseNatureName.substr(0,2):'';
          list[i].group_time={hour:'00',minute:'00',second:'00'};
          list[i].show_more=false;
          list[i].group_type=list[i].groupFound.endTime/1000-parseInt(new Date().getTime())/1000>0?true:false;
          list[i].order.payStep=list[i].order.orderType==1?4:5;
          var joins=list[i].groupJoins;
          for(var m=0;m<joins.length;m++){
            if(joins[m].userId==userinfo.id){
              join_index=m
            }
          }
          //
          my.get_meal_detail({"id":list[i].order.setMealId}).then(res=>{
            if(res.data.code==200){
              var info=res.data.data;
              lessonTimes.push(info.lessonTime)
            }
          })
        }
        that.setData({join_index:join_index,lessonTimes:lessonTimes})
        var order_list = that.data.order_list;
        order_list = util.extend(order_list, list);
        if (list.length < pageSize) {
          that.setData({
            order_list: order_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            order_list: order_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(list.length>0||order_list.length>0){
          that.group_count_down()
        }
        if(list.length==0&&order_list.length==0){
          that.setData({show_nav:true})
        }
      }
    })
  },
  // 订单列表
  get_order_list:function(type){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize,token=that.data.token;
    clearInterval(that.data.timeGroup);
    var params={
      "currentPage": currentPage,
      "pageSize": pageSize,
      "paymentStatus": type
    }
    my.get_order_list(params,token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].commodityImg=list[i].commodityImg?(list[i].commodityImg.indexOf("[")>-1?list[i].commodityImg.replace(/\[|]/g,'').split(","):list[i].commodityImg.split(",")):'';
          list[i].courseNatureName=list[i].courseNatureName?list[i].courseNatureName.substr(0,2):''
          list[i].payTime=util.formatTime_order(new Date(list[i].paymentTime))
          list[i].group_time={hour:'00',minute:'00',second:'00'}
          list[i].show_more=false
        }
        var order_list = that.data.order_list;
        order_list = util.extend(order_list, list);
        if (list.length < pageSize) {
          that.setData({
            order_list: order_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            order_list: order_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(type==1){
          if(list.length>0||order_list.length>0){
            that.count_down();
          }
        }else{
          clearInterval(that.data.timer);
        }
        if(list.length==0&&order_list.length==0){
          that.setData({show_nav:true})
        }
      }
    })
  },
  // 订单课程套餐
  get_meal_detail:function(id,index){
    var that=this,order_list=that.data.order_list;
    my.get_meal_detail({"id":id}).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        order_list[index].show_more=true
        that.setData({meal_info:info,order_list:order_list})
      }
    })
  },
  // 排课暂时废弃
  // 获取排课表
  get_less_list:function(id){
    var that=this;
    my.get_less_list({"orderId":id}).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          list[i].pitch='第'+util.convertToChinaNum(i+1)+'节'
          list[i].month_time= util.formatTime_month_else(new Date(list[i].startTime))
          list[i].week=util.getweekday(util.formatTime_age(new Date(list[i].startTime)))
          list[i].start=util.formatTime_time(new Date(list[i].startTime))
          list[i].end=util.formatTime_time(new Date(list[i].endTime))
        }
        that.setData({com_data:list})
      }
    })
  },
  // 确认排课
  confirm_table:function(id){
    var that=this,token=that.data.token,order_list=that.data.order_list,order_index=that.data.order_index;
    my.confirm_table({"id":id},token).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('确认排课成功',2000)
        order_list[order_index].reverseStatus=3
        that.setData({order_list:order_list})
      }
    })
  },
  // 取消排课
  cancel_table:function(id){
    var that=this,token=that.data.token,order_list=that.data.order_list,order_index=that.data.order_index;
    my.cancel_table({"id":id},token).then(res=>{
      if(res.data.code==200){
        app.globalData.change_table=true
        order_list[order_index].reverseStatus=1
        that.setData({call_show:false,order_list:order_list})
      }
    })
  },
  // 取消订单
  cancel_order:function(id,index){
    var that=this,order_list=that.data.order_list;
    my.cancel_order({"id":id}).then(res=>{
      if(res.data.code==200){
        clearInterval(that.data.timer);
        order_list.splice(index, 1);
        that.setData({order_list:order_list})
        if(order_list.length>0){
          that.count_down();
        }else{
          that.setData({show_nav:true})
        }
        that.get_order_count();
      }
    })
  },
  // 取消报名
  cancel_exp_order:function(id,index){
    var that=this,order_list=that.data.order_list;
    my.cancel_order({"id":id}).then(res=>{
      if(res.data.code==200){
        order_list.splice(index, 1);
        that.setData({order_list:order_list})
        util.page_show_toast('取消报名成功',2000)
        //
        that.get_order_count();
      }
    })
  },
  // 删除订单
  user_delt_order:function(id,index){
    var that=this,order_list=that.data.order_list;
    my.cancel_order({"id":id}).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('删除订单成功',2000)
        order_list.splice(index, 1);
        that.setData({order_list:order_list})
        that.get_order_count();
      }
    })
  },
  // 拼团支付尾款
  create_goup_order:function(index){
    var that=this,order_list=that.data.order_list,token=that.data.token;
    var params={
      "activityId": order_list[index].order.activityId,
      "childId": order_list[index].order.childId,
      "buyerNotes": order_list[index].order.sellerNotes?order_list[index].order.sellerNotes:'',
      "childName": order_list[index].order.childName,
      "courseImg": order_list[index].order.commodityImg[0],
      "appId": 1001,
      "orderType": 2,
      "groupFoundId": order_list[index].order.groupFoundId,
      "groupJoinId": order_list[index].order.groupJoinId,
      "groupType": 2
    }
    group.create_goup_order(params,token).then(res=>{
      if(res.data.code==200){
        wx.hideLoading({})
        var info=res.data.data;
        //
        that.pay_order(info.id,info.orderNo,token,info.paidInAmount,0,info.targetType,2,'')
      }else{
        that.setData({pay_act:true})
        util.page_show_toast(res.data.message,2000);
      }
    })
  },
  // 支付订单
  pay_order:function(orderId,orderNo,token,order_price,pref_money,targetType,type,group_aid){
    var that=this,payStep=that.data.payStep,activity_id=that.data.activityId;
    var params={
      "orderNo": orderNo,
      "payType": 3,
      "openId":app.globalData.openId
    }
    home.pay_order(params,token).then(res=>{
      if(res.data.code==200){
        var data=JSON.parse(res.data.data);
        // 微信支付
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success:function(res){
            // type 1-待支付 2-拼团支付尾款
            if(type==1){
              clearInterval(that.data.timer);
              // targetType 4-拼团单
              if(targetType==4){
                that.setData({order_list:[],nav_index:5,currentPage:1,pay_act:true})
                setTimeout(function(){
                  that.get_group_order(5);
                },500)
              }else{
                that.setData({order_list:[],nav_index:2,currentPage:1,pay_act:true})
                setTimeout(function(){
                  that.get_order_count();
                  that.get_order_list(2);
                },500)
              }
              wx.navigateTo({
                url:'../../pages/paySuccess/paySuccess?type=2&index=1&price='+order_price+'&money='+pref_money+'&aid='+activity_id+'&payStep='+payStep+'&orderId='+orderId+'&group_aid='+group_aid,
              })
            }else{
              clearInterval(that.data.timeGroup);
              that.setData({order_list:[],nav_index:5,currentPage:1,pay_act:true})
              util.page_show_toast("支付成功",2000)
              setTimeout(function(){
                that.get_group_order(5);
              },500)
            }
            // 增加次数
            that.get_count_after()
          },
          fail:function(res){
            // util.page_show_toast('支付失败',2000)
            that.setData({pay_act:true})
          }
        })
      }
    })
  },
  // 退款
  refund_order:function(params,token){
    var that=this,order_list=that.data.order_list,order_index=that.data.order_index;
    my.refund_order(params,token).then(res=>{
      if(res.data.code==200){
        if(res.data.data){
          util.page_show_toast('退款成功',2000)
        }
        order_list.splice(order_index, 1);
        that.setData({order_list:order_list})
        that.get_order_count();
      }
    })
  },
  // 查询订单课程状态
  get_course_type:function(id){
    var that=this,token=that.data.token;
    var params={
      "courseId": id
    }
    my.get_course_type(params,token).then(res=>{
      if(res.data.code==200){
        if(res.data.data==3){
          wx.navigateTo({
            url: '../../pages/courseDetail/courseDetail?id='+id+'&status=7',
          })
        }else{
          util.page_show_toast("课程或商品已下架，相关服务请联系客服",2000)
        }
      }else{
        util.page_show_toast("课程或商品已下架，相关服务请联系客服",2000)
      }
    })
  },
  // 查询订单拼团状态
  get_group_type:function(id){
    var params={
      "id": id
    }
    group.get_group_type(params).then(res=>{
      if(res.data.code==200){
        var status=res.data.data;
        if(status==2){
          wx.navigateTo({
            url: '../../pages/groupCourse/groupCourse?id='+id,
          })
        }else if(status==3){
          util.page_show_toast("该拼团活动已结束",2000)
        }
      }else{
        util.page_show_toast("该拼团活动已下架，相关服务请联系客服",2000)
      }
    })
  },
  // 重置抽奖次数
  get_count_after:function(){
    var that=this,token=that.data.token,activity_id=that.data.activity_id;
    var params={
      "activityId": activity_id
    }
    config.get_count_after(params,token).then(res=>{
      
    })
  },
  // 活动详情
  get_cour_and_group:function(id,cour_details){
    var that=this;
    var params={
      "id":id,
      "lat": that.data.city.lat,
      "lng": that.data.city.lng
    }
    group.get_cour_and_group(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        cour_details.activityId=id;
        cour_details.count=info.course.initialRegistrationCount;
        cour_details.groupPrice=info.activityGroup.groupPrice;
        cour_details.setMealPrice=info.setMeal.price;
        cour_details.deposit=info.activityGroup.deposit;
        cour_details.lessonTime=info.course.lessonTime;
        cour_details.setMealId=info.activityGroup.setMealId;
        if(info.activityGroup.deposit==1){
          that.setData({payStep:4})
        }else{
          that.setData({payStep:5})
        }
        wx.setStorageSync('cour_details', cour_details)
      }
    })
  },
})